/**
 * @author harry
 * @date 2021/12/5/10:09
 */

package com.ui.contact;

import com.controller.ContactController;
import com.pojo.Contact;
import com.ui.builder.ButtonBuilder;
import com.ui.builder.LabelBuilder;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class DeleteContact extends JFrame implements ActionListener {
    private final JPanel labelPanel = new JPanel();
    private final JPanel buttonPanel = new JPanel();
    private final JLabel notice = LabelBuilder.makeLabel("您确认要删除吗？");
    private final JButton agree = ButtonBuilder.makeButton("确认");
    private final JButton cancel = ButtonBuilder.makeButton("取消");
    private final ContactController contactController = new ContactController();
    private Contact chosenContact;

    public DeleteContact(Contact chosenContact) {
        super("删除联系人");
        if(chosenContact == null) return;
        this.chosenContact = chosenContact;

        agree.addActionListener(this);
        cancel.addActionListener(this);

        labelPanel.setLayout(new GridLayout(2,1, 0, 0));
        buttonPanel.setLayout(new GridLayout(1,2,30, 0));

        labelPanel.add(notice);
        labelPanel.add(new JLabel());
        buttonPanel.add(agree);
        buttonPanel.add(cancel);

        this.setLayout(new FlowLayout());
        this.setSize(300, 150);
        this.setLocationRelativeTo(null);
        this.add(labelPanel);
        this.add(buttonPanel);
        this.setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        Object source = e.getSource();
        if (source == agree) {
            boolean result = contactController.deletePerson(chosenContact);
            if(result) {
                JOptionPane.showMessageDialog(null, "删除成功");
            }
            else {
                JOptionPane.showMessageDialog(null, "删除失败");
            }
        }
        this.setVisible(false);
    }
}
